package sdp;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Hashtable;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.WindowConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;


public class ControlPanel extends JFrame {
	static public interface SliderCallback {
		void valueChanged( JSlider s, int newValue );
	}
	
	static public interface ButtonCallback {
		void buttonClicked(JButton b);
	}
	
	public void addSlider( String name, int init, int min, int max, SliderCallback callback ) {
		JLabel  label  = new JLabel(name, JLabel.CENTER);
		JSlider slider = new JSlider(JSlider.HORIZONTAL,min,max,init);
		slider.addChangeListener( new SliderCallBackAdapter( callback ) );
		slider.setBorder( BorderFactory.createEmptyBorder(0,0,10,0) );
		panel.add( label );
		panel.add( slider );
		pack();
	}
	
	public void addButton( String name, ButtonCallback callback) {
		JButton	button = new JButton(name);
		button.addActionListener( new ButtonCallbackAdapter(callback));
		panel.add(button);
		pack();
	}
	
	public JSlider getSlider( String name ) {
		int n = panel.getComponentCount() - 1;
		
		for( int i = 0 ; i < n ; ++ i ) {
			if( panel.getComponent(i) instanceof JLabel && panel.getComponent(i+1) instanceof JSlider ) {
				JLabel l = (JLabel) panel.getComponent( i );
				if( l.getText().equals(name) )
					return (JSlider) panel.getComponent( i + 1 );
			}
		}
		
		return null;
	}
	
	public ControlPanel() {
		super("Control Panel");
		add( panel = new JPanel() );
		panel.setLayout(new GridLayout(0,1) );
		setVisible(true);
		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
	}
	
	static private class SliderCallBackAdapter implements ChangeListener {
		private SliderCallback cb;
		
		public SliderCallBackAdapter( SliderCallback cb ) {
			this.cb = cb;
		}
		
		@Override
		public void stateChanged(ChangeEvent e) {
			JSlider source = (JSlider)e.getSource();
			//if (!source.getValueIsAdjusting())
			cb.valueChanged( source, (int)source.getValue() );
		}
	}
	
	static private class ButtonCallbackAdapter implements ActionListener {
		
		private ButtonCallback callback;
		
		public ButtonCallbackAdapter( ButtonCallback cb ) {
			this.callback = cb;
		}

		@Override
		public void actionPerformed(ActionEvent e) {
			JButton source = (JButton)e.getSource();
			callback.buttonClicked(source);
			
		}
		
	}
	
	private Hashtable<String, SliderCallback> sliders;
	private JPanel panel;
}
